package util.concurrent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时执行
 */
public class ExecutorService_ {
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static ScheduledExecutorService exec = Executors.newScheduledThreadPool(2);

    public static void main(String[] args) {
        ExecutorService_ ex = new ExecutorService_();
        ex.test3();
    }


    public void test1() {
        exec.scheduleAtFixedRate(() -> out(), 0, 20, TimeUnit.SECONDS);
    }

    public void test2() {


        //异常要处理 否则 结束定时执行   虽然抛出了运行异常,当被拦截了,next周期继续运行
        exec.scheduleAtFixedRate(() -> {
            try {
                out();
                Thread.sleep(2000);  //睡眠无效
                out();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 0, 2, TimeUnit.SECONDS);
    }


    public void test3() {
        /**
         * 创建并执行一个在给定初始延迟后首次启用的定期操作，
         * 随后，在每一次执行终止和下一次执行开始之间都存在给定的延迟。
         */
//        exec.scheduleWithFixedDelay(() -> {
//            System.out.println(format.format(new Date())+"---------------");
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }, 0, 3, TimeUnit.SECONDS);


        exec.scheduleWithFixedDelay(() -> {
            out();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 0, 3, TimeUnit.SECONDS);
    }


    private static void out() {
        System.out.println(format.format(new Date()));
    }
}
